package com.genius.workflow.ehcache;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.springframework.core.io.ClassPathResource;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;


public class CacheUtils {
	
	private static CacheUtils instance = null;
	
	private CacheManager cacheManager;
	
	private CacheUtils(){
		try {
			ClassPathResource resouce = new ClassPathResource("\\ehcache.xml");
			InputStream in = resouce.getInputStream();
			cacheManager = CacheManager.create(in);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static CacheUtils cacheUtils(){
		if(instance == null){
			instance = new CacheUtils();
		}
		
		return instance;
	}

	
	public void addCache(String name){
		if(!cacheManager.cacheExists(name)){
			cacheManager.addCache(name);
		}
	}
	
	private Cache getCache(String name){
		return cacheManager.getCache(name);
	}
	public void removeCache(String name){
		cacheManager.removeCache(name);
	}
	
	public void addElement(String name, Object key, Object value){
//		if(containsKey(name, key)){
//			removeElement(name, key);
//		}
		Element element = new Element(key,value);
		getCache(name).put(element);
	}
	
	public Object getElement(String name, Object key){
		Element element = getCache(name).getQuiet(key);
		if(element == null){
			return null;
		}
		return element.getObjectValue();
	}
	public boolean removeElement(String name, Object key){
		System.out.println(name + key);
		return getCache(name).remove(key);
	}
	
	public List<Object> getKeys(String name){
		@SuppressWarnings("unchecked")
		List<Object> keys = getCache(name).getKeysNoDuplicateCheck();
		return keys;
	}
	
	public void removeAll(String name){
		Cache cache = getCache(name);
		if(cache != null){
			cache.removeAll();
		}
	}
	
	public boolean containsKey(String name, Object key){
		return getCache(name).isElementInMemory(key);
	}
	
	public int size(String name){
		return getCache(name).getSize();
	}
	public CacheManager getCacheManager() {
		// TODO Auto-generated method stub
		return cacheManager;
	}
}
